/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-02-20
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-04-24
 * @Description: 
 */
// 信息输入框
import 'package:chat_client/models/session_model.dart';
import 'package:chat_client/utils/image-picker/image_picker_helper.dart'
    show ImagePickerHelper;
import 'package:flutter/material.dart';
import 'package:chat_client/enums/chat_enum.dart' show PanelType;
import 'package:chat_bottom_container/chat_bottom_container.dart';
import 'package:image_picker/image_picker.dart';

import 'emoji_panel.dart';
import 'tools_panel.dart';

import 'package:chat_client/router/router.dart';
import 'package:chat_client/screens/chat/widgets/voice.dart';

class InputBar extends StatefulWidget {
  final TextEditingController textController;
  final Function(dynamic) onSend;
  final SessionModel session;

  const InputBar({
    super.key,
    required this.textController,
    required this.session,
    required this.onSend,
  });

  @override
  InputBarState createState() => InputBarState();
}

class InputBarState extends State<InputBar> {
  // 面板控制器
  final _panelontroller = ChatBottomPanelContainerController<PanelType>();
  // 输入框的焦点对象
  final FocusNode _inputFocusNode = FocusNode();

  // 控制发送按钮
  bool _hasText = false;

  // 现在的面板
  PanelType _currentPanel = PanelType.none;

  // 关闭底部功能面板
  Function get closePanel => _closePanel;

  XFile? _selectedImage; // 文件对象

  _closePanel() {
    if (!mounted) return; // 防止组件销毁后调用
    _panelontroller.updatePanelType(ChatBottomPanelType.other,
        data: PanelType.keyboard);
  }

  @override
  void dispose() {
    widget.textController.removeListener(_updateTextStatus);
    _inputFocusNode.removeListener(_handleFocusChange);
    _inputFocusNode.dispose();
    super.dispose();
  }

  // 修改按钮可见
  void _updateTextStatus() {
    setState(() {
      _hasText = widget.textController.text.isNotEmpty;
    });
  }

  // 获取焦点时，设置_currentPanel为keyboard，（针对手动点击优化）
  void _handleFocusChange() {
    if (_inputFocusNode.hasFocus) {
      setState(() {
        _currentPanel = PanelType.keyboard;
      });
    }
  }

  // 面板控制
  _switchPannel(PanelType panel) {
    if (panel == _currentPanel) {
      _inputFocusNode.requestFocus(); // 获取焦点，唤起键盘
    } else {
      _panelontroller.updatePanelType(ChatBottomPanelType.other, data: panel);
      setState(() {
        _currentPanel = panel == _currentPanel ? PanelType.keyboard : panel;
      });
    }
  }

  // 表情添加
  addEmoji(String emoji) {
    widget.textController.text += emoji;
  }

  // 表情删除
  removeEmoji(String emoji) {
    // widget.textController.text += emoji;
  }

  late final List<ToolAction> _toolActions;

  /// 选择图片
  Future<void> pickImage() async {
    try {
      final file =
          await ImagePickerHelper.pickAndProcessImage(enableFreeStyle: true);
      if (file == null) return;
      _selectedImage = file;
    } catch (e) {
      print('图片处理失败${e.toString()}');
    }
  }

  @override
  void initState() {
    super.initState();
    // 当被监听对象状态变化时自动触发回调
    widget.textController.addListener(_updateTextStatus);
    // 添加焦点变化监听
    _inputFocusNode.addListener(_handleFocusChange);

    // 面板控制器
    _toolActions = [
      ToolAction(
          icon: Icons.photo,
          label: '照片',
          type: 'photo',
          onAction: () async {
            // 选择图片
            await pickImage();
            // 发送图片
            if (_selectedImage == null) return;
            widget.onSend(_selectedImage);
            // 释放图片资源
            ImagePickerHelper.releaseImage(_selectedImage);
          }),
      ToolAction(
          icon: Icons.folder_open,
          label: '文件',
          type: 'file',
          onAction: () => {}),
      ToolAction(
          icon: Icons.videocam, label: '视频', type: 'vedio', onAction: () => {}),
      ToolAction(
          icon: Icons.call,
          label: '语音',
          type: 'voice',
          onAction: () => RouteManager.navigateToWidget(
              VoiceCallScreen(session: widget.session))),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
        duration: Duration(milliseconds: 500),
        decoration: BoxDecoration(
          border: Border(top: BorderSide(color: Colors.grey.shade200)),
          color: Color(0XFFF7F7F7),
        ),
        child: Column(
          children: [
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10, horizontal: 4),
              child: Row(
                children: [
                  // 语音
                  IconButton(
                    icon: Icon(
                        _currentPanel == PanelType.voice
                            ? Icons.keyboard
                            : Icons.mic,
                        size: 30),
                    onPressed: () {
                      _switchPannel(PanelType.voice);
                    },
                  ),
                  // 输入框
                  Expanded(
                      child: TextField(
                    controller: widget.textController,
                    focusNode: _inputFocusNode,
                    onSubmitted: widget.onSend,
                    style: TextStyle(
                      fontSize: 22.0, // 设置字体大小
                      color: Colors.black87,
                    ),
                    decoration: InputDecoration(
                        contentPadding:
                            EdgeInsets.symmetric(horizontal: 10, vertical: 4)),
                  )),
                  // 表情包
                  IconButton(
                    icon: Icon(
                      _currentPanel == PanelType.emoji
                          ? Icons.keyboard
                          : Icons.sentiment_satisfied,
                      size: 30,
                    ),
                    onPressed: () {
                      _switchPannel(PanelType.emoji);
                    },
                  ),
                  // 更多
                  IconButton(
                    icon: Icon(
                      Icons.add_circle_outline,
                      size: 30,
                    ),
                    onPressed: () {
                      _switchPannel(PanelType.tool);
                    },
                  ),
                  // 发送按钮
                  AnimatedContainer(
                    height: 40,
                    duration: Duration(milliseconds: 200),
                    curve: Curves.easeInOut,
                    width: _hasText ? 64 : 0,
                    child: ElevatedButton(
                      onPressed: () =>
                          widget.onSend(widget.textController.text),
                      child: FittedBox(
                        fit: BoxFit.scaleDown, // 保证文字适应容器
                        child: Text('发送'),
                      ),
                    ),
                  )
                ],
              ),
            ),
            // 底部容器
            _buildPanelContainer(),
          ],
        ));
  }

  // 构建底部面板盒子
  Widget _buildPanelContainer() {
    return ChatBottomPanelContainer<PanelType>(
      controller: _panelontroller,
      inputFocusNode: _inputFocusNode,
      otherPanelWidget: (type) {
        // 返回自定义的面板视图
        if (type == null) return const SizedBox.shrink();
        switch (type) {
          case PanelType.emoji: // 表情面板
            return EmojiPickerPanel(
              onTap: addEmoji,
            );
          case PanelType.tool: // 其它工具面板
            return ToolPanel(actions: _toolActions);
          default:
            return const SizedBox.shrink();
        }
      },
      // 底部面板容器背景色
      panelBgColor: Colors.transparent,
      safeAreaBottom: 10,
    );
  }
}
